package com.qcq.wecheck.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qcq.wecheck.constant.WxDeveloperConstant;
import com.qcq.wecheck.service.WebService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author O
 * @version 1.0
 * @since 2018/10/17
 */
@Service
@Slf4j
public class WebServiceImpl implements WebService {
	@Resource
	private RestTemplate restTemplate;

	@Override
	public String getOpenId(String jsCode) {
		String url = WxDeveloperConstant.getFullUrl(jsCode);
		Map<String, String> params = new HashMap<>();
		String result = restTemplate.getForObject(url, String.class, params);
		log.info("get openid result : {}" + result);
		Map<String, Object> map = JSONObject.parseObject(result, Map.class);
		Object openId = map.get("openid");
		Object errMsg = map.get("errmsg");
		if (errMsg != null) {
			log.error("error getting open id : {}", errMsg.toString());
		}

		return openId != null ? openId.toString() : null;
	}
}
